package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    MenuService menuService;
    @RequestMapping("/findPage")
    @PreAuthorize("hasAuthority('MENU_QUERY')")//权限校验
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult=  menuService.findPage(queryPageBean);
        return pageResult;

    }

    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('MENU_ADD')")//权限校验
    public Result add(@RequestBody Menu menu){
        try {
            menuService.add(menu);
            return new Result(true, MessageConst.ADD_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ADD_MENU_FALL);
        }
    }
    @RequestMapping("/delById")
    @PreAuthorize("hasAuthority('MENU_DELETE')")//权限校验


    public Result delById(Integer id){
        try {
            menuService.delById(id);
            return new Result(true,MessageConst.DELETE_MENU_SUCCESS);
        }catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.DELETE_MENU_FALL);
        }
    }

    @RequestMapping("/findById")
    @PreAuthorize("hasAuthority('MENU_QUERY')")//权限校验

    public Result findById(Integer id){
        try {
            Menu menu=  menuService.findById(id);
            return new Result(true, MessageConst.QUERY_MENU_SUCCESS,menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_MENU_FALL);
        }
    }


    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('MENU_EDIT')")//权限校验

    public Result edit(@RequestBody Menu menu){
        try {
            menuService.edit(menu);
            return new Result(true,MessageConst.EDIT_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.EDIT_MENU_FALL);
        }
    }
    @RequestMapping("/findAll")
    @PreAuthorize("hasAuthority('MENU_QUERY')")//权限校验

    public  Result findAll(){
        List<Menu> menuList= menuService.findAll();
        return new Result(true,MessageConst.ADD_MENU_SUCCESS,menuList);
    }
}
